using System;
using System.Xml;
using System.Text;
using System.Collections.Generic;
using InfoCenter.Agent.Helpers;
using System.IO;
using System.Drawing;
namespace SXDClient
{
    public class Listener
    {
        private int _timeout;

        public int Timeout
        {
            get { return _timeout; }
            set { _timeout = value; }
        }

        public Listener()
            : this(60000)
        {
        }
        SXDBLClient proxy;
        string result = "";
        string rawMessage = "";
        string command = "";
        int nLEDID = 1;
        int nScreenType = 1;
        int nWidth = 238;
        int nHeight = 32;
        Int64 leattime = 500;
        string szBmpName = "A1.jpg";
        byte[] imgbyte;
        Image img;
        string bmp = "";

        public Listener(int timeoutInterval)
        {
            Timeout = timeoutInterval;
        }
        public static byte[] GetBytesByImage(System.Drawing.Image image)
        {
            byte[] photo_byte = null;
            using (MemoryStream ms = new MemoryStream())
            {
                Bitmap bmp = new Bitmap(image);
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                photo_byte = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(photo_byte, 0, Convert.ToInt32(ms.Length));
                bmp.Dispose();
            }

            return photo_byte;
        }
        private byte[] ByteArrayFromBitmap(ref Bitmap bitmap)
        {
            // The bitmap contents are coded with Width and Height followed by pixel colors (uint)
            byte[] b = new byte[4 * (bitmap.Height * bitmap.Width + 2)];
            int n = 0;
            // encode the width
            uint x = (uint)bitmap.Width;
            int y = (int)x;
            b[n] = (byte)(x / 0x1000000);
            x = x % (0x1000000);
            n++;
            b[n] = (byte)(x / 0x10000);
            x = x % (0x10000);
            n++;
            b[n] = (byte)(x / 0x100);
            x = x % 0x100;
            n++;
            b[n] = (byte)x;
            n++;
            // encode the height
            x = (uint)bitmap.Height;
            y = (int)x;
            b[n] = (byte)(x / 0x1000000);
            x = x % (0x1000000);
            n++;
            b[n] = (byte)(x / 0x10000);
            x = x % (0x10000);
            n++;
            b[n] = (byte)(x / 0x100);
            x = x % 0x100;
            n++;
            b[n] = (byte)x;
            n++;
            // Loop through each row
            for (int j = 0; j < bitmap.Height; j++)
            {
                // Loop through the pixel on this row
                for (int i = 0; i < bitmap.Width; i++)
                {
                    x = (uint)bitmap.GetPixel(i, j).ToArgb();
                    y = (int)x;
                    b[n] = (byte)(x / 0x1000000);
                    x = x % (0x1000000);
                    n++;
                    b[n] = (byte)(x / 0x10000);
                    x = x % (0x10000);
                    n++;
                    b[n] = (byte)(x / 0x100);
                    x = x % 0x100;
                    n++;
                    b[n] = (byte)x;
                    n++;
                }
            }
            return b;
        }
        private void ScreenInit(int width, int height)
        {
            #region============LED_LEDScreenInit================
            command = "LED_LEDScreenInit";
            rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                  "<SXDData>" +
                  "<COMMAND>" + command + "</COMMAND>" +
                  "<LEDID>" + nLEDID + "</LEDID>" +
                  "<SCREENTYP>" + nScreenType + "</SCREENTYP>" +
                  "<WIDTH>" + width + "</WIDTH>" +
                  "<HEIGHT>" + height + "</HEIGHT>" +
                  "</SXDData>";
            result = proxy.GetInfo(rawMessage);
            #endregion
        }
        private void EndProg()
        {
            #region============LED_EndProgram================
            command = "LED_EndProgram";
            rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                  "<SXDData>" +
                      "<COMMAND>" + command + "</COMMAND>" +
                  "<LEDID>" + nLEDID + "</LEDID>" +
                  "</SXDData>";
            result = proxy.GetInfo(rawMessage);
            #endregion
        }
        private void Send2LED()
        {
            #region============LED_SendToScreen================
            command = "LED_SendToScreen";
            rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                  "<SXDData>" +
                      "<COMMAND>" + command + "</COMMAND>" +
                  "<LEDID>" + nLEDID + "</LEDID>" +
                  "</SXDData>";
            result = proxy.GetInfo(rawMessage);
            #endregion
        }
        private void StartUpAndShowIP()
        {
            string ip = SwithPower(1, 1);
            ScreenInit(128, 32);
            AddText("Id:" + nLEDID + ip,"ËÎÌå",12,1,1);
            EndProg();
            Send2LED();
        }
        private void BeginProg(int time = 1000)
        {
            command = "LED_BeginProgram";
            leattime = time;
            string szBackBMP = "";// System.IO.Path.Combine(PathHelper.ApplicationPath, @"LPhoto\" + "A2.jpg");
            rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                  "<SXDData>" +
                      "<COMMAND>" + command + "</COMMAND>" +
                  "<LEDID>" + nLEDID + "</LEDID>" +
                  "<LEAFTIME>" + leattime + "</LEAFTIME>" +
                  "<BACKGROUDBMP>" + szBackBMP + "</BACKGROUDBMP>" +
                  "</SXDData>";
            result = proxy.GetInfo(rawMessage);

        }
        private void AddText(string text, string fontname = "ËÎÌå", int fontsize = 16, int effect = 0, int speed = 1)
        {

            BeginProg(1000);

            string szText = text;
            command = "LED_AddTextBlock";
            string szFontName = fontname;
            int lFontSize = fontsize;
            int lFontColor = 234;
            int nBold = 1;
            int nUnderline = 1;
            int nStrick = 1;
            int nEffectType = effect;
            int nSpeed = speed;
            Int32 lTrasnparent = 1;
            int startx = 10;
            int starty = 2;
            nWidth = 128;
            nHeight = 32;
            rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                  "<SXDData>" +
                      "<COMMAND>" + command + "</COMMAND>" +
                  "<LEDID>" + nLEDID + "</LEDID>" +
                  "<TEXT>" + szText + "</TEXT>" +
                  "<STARTX>" + startx + "</STARTX>" +
                  "<STARTY>" + starty + "</STARTY>" +
                  "<WIDTH>" + nWidth + "</WIDTH>" +
                  "<HEIGHT>" + nHeight + "</HEIGHT>" +
                  "<FONTNAME>" + szFontName + "</FONTNAME>" +
                  "<FONTSIZE>" + lFontSize + "</FONTSIZE>" +
                  "<FONTCOLOR>" + lFontColor + "</FONTCOLOR>" +
                  "<FONTBOLD>" + nBold + "</FONTBOLD>" +
                  "<FONTUNDERLINE>" + nUnderline + "</FONTUNDERLINE>" +
                  "<FONTSTRICK>" + nStrick + "</FONTSTRICK>" +
                  "<EFFECTTYPE>" + nEffectType + "</EFFECTTYPE>" +
                  "<SPEED>" + nSpeed + "</SPEED>" +
                  "<TRANSPARENT>" + lTrasnparent + "</TRANSPARENT>" +
                  "</SXDData>";
            result = proxy.GetInfo(rawMessage);
        }
        private void AddPicture(string picname, int startx, int starty, int width,int height, int effect = 0, int speed = 1)
        {

            BeginProg(1000);
            string szBmp = picname;
            command = "LED_AddBmpBlock";
            int nEffectType = effect;
           int nSpeed = 1;
           int lTrasnparent = 1;
           int x = startx;
           int y = startx;
            nWidth = width;
            nHeight = height;
            rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                  "<SXDData>" +
                      "<COMMAND>" + command + "</COMMAND>" +
                  "<LEDID>" + nLEDID + "</LEDID>" +
                  "<PICTURE>" + szBmp + "</PICTURE>" +
                  "<STARTX>" + x + "</STARTX>" +
                  "<STARTY>" + y + "</STARTY>" +
                  "<WIDTH>" + nWidth + "</WIDTH>" +
                  "<HEIGHT>" + nHeight + "</HEIGHT>" +
                  "<EFFECTTYPE>" + nEffectType + "</EFFECTTYPE>" +
                  "<SPEED>" + nSpeed + "</SPEED>" +
                  "<TRANSPARENT>" + lTrasnparent + "</TRANSPARENT>" +
                  "</SXDData>";
            result = proxy.GetInfo(rawMessage);
        }
        private void RegPicture(string szBMP)
        {

            command = "LED_SavePicture";
            img = System.Drawing.Image.FromFile("/home/sun/SXDFile/Temp/"+ szBMP);
            //img = System.Drawing.Image.FromFile("D:/SXDFile/Temp/" + szBMP);
            //szBmpName = "A1.jpg";
            imgbyte = GetBytesByImage(img);
            img.Dispose();
            bmp = Convert.ToBase64String(imgbyte);
            rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                  "<SXDData>" +
                  "<COMMAND>" + command + "</COMMAND>" +
                  "<PICTURENAME>" + szBmpName + "</PICTURENAME>" +
                  "<PVALUE>" + bmp + "</PVALUE>" +
                  "</SXDData>";
            result = proxy.GetInfo(rawMessage);

        }
        private void AdjustCurrentTime()
        {
            command = "LED_AdjustCurrentTime";
            rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                  "<SXDData>" +
                      "<COMMAND>" + command + "</COMMAND>" +
                  "<LEDID>" + nLEDID + "</LEDID>" +
                  "</SXDData>";
            result = proxy.GetInfo(rawMessage);
        }
        private void AddClock()
        {
            BeginProg(5000);
            #region============ LED_AddClockBlockÌí¼ÓÊ±ÖÓ================
         
            command = "LED_AddClockBlock";
            int nSpeed = 1;
            int lTrasnparent = 1;
            int startx = 10;
            int starty = 2;
            nWidth = 128;
            nHeight = 32;
            string szFontName = "宋体";
            int lFontSize = 16;
            int lFontColor = 234;
            int nBold = 1;
            int nUnderline = 1;
            int nStrick = 1;
            int nEffectType = 0;
            nSpeed = 1;
            lTrasnparent = 1;
            startx = 10;
            starty = 2;
            nWidth = 128;
            nHeight = 32;
            rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                  "<SXDData>" +
                      "<COMMAND>" + command + "</COMMAND>" +
                  "<LEDID>" + nLEDID + "</LEDID>" +
                  "<STARTX>" + startx + "</STARTX>" +
                  "<STARTY>" + starty + "</STARTY>" +
                  "<WIDTH>" + nWidth + "</WIDTH>" +
                  "<HEIGHT>" + nHeight + "</HEIGHT>" +
                  "<FONTNAME>" + szFontName + "</FONTNAME>" +
                  "<FONTSIZE>" + lFontSize + "</FONTSIZE>" +
                  "<FONTCOLOR>" + lFontColor + "</FONTCOLOR>" +
                  "<FONTBOLD>" + nBold + "</FONTBOLD>" +
                  "<FONTUNDERLINE>" + nUnderline + "</FONTUNDERLINE>" +
                  "<FONTSTRICK>" + nStrick + "</FONTSTRICK>" +
                  "<EFFECTTYPE>" + nEffectType + "</EFFECTTYPE>" +
                  "<SPEED>" + nSpeed + "</SPEED>" +
                  "<TRANSPARENT>" + lTrasnparent + "</TRANSPARENT>" +
                  "</SXDData>";
            result = proxy.GetInfo(rawMessage);
            #endregion
        }
        private string GetBright()
        {
            #region============LED_GetBright================
            command = "LED_GetBright";
            rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                  "<SXDData>" +
                      "<COMMAND>" + command + "</COMMAND>" +
                  "<LEDID>" + nLEDID + "</LEDID>" +
                  "</SXDData>";
            result = proxy.GetInfo(rawMessage);
            #endregion
            return result;
        }
        private string SetBright(int nBright)
        {
            #region============LED_GetBright================
            command = "LED_SetBright";
            rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                  "<SXDData>" +
                      "<COMMAND>" + command + "</COMMAND>" +
                  "<LEDID>" + nLEDID + "</LEDID>" +
                  "<BRIGHT>"+nBright+"</BRIGHT>" +                  
                  "</SXDData>";
            result = proxy.GetInfo(rawMessage);
            #endregion
            return result;
        }
        private void RegLED()
        {
            #region=======3.7 LED_RegLED-LED03================
            // 3.6. ½ØÍ¼
            //¿ÉÒÔÍ¨¹ýÖÐÐÄ¹ÜÀíÆ½Ì¨£¬·¢ËÍ½ØÍ¼Ö¸Áî£¬½«µ±Ç°LEDµÄÏÔÊ¾ÄÚÈÝÒÔÍ¼Æ¬µÄ·½Ê½·µ»Ø¡£
            command = "LED_RegLED";
            rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                  "<SXDData>" +
                  "<COMMAND>" + command + "</COMMAND>" +
                  "<LEDID>3</LEDID>" +
                  "<LLLEDPRE>  </LLLEDPRE>" +
                  "<LLLEDNUMBER>LED01</LLLEDNUMBER>" +
                  "<IPADDRESS>192.168.0.101</IPADDRESS>" +
                  "<DEVTYPE>DEVICE_TYPE_UDP</DEVTYPE>" +
                  "<DSPEED>SBR_57600</DSPEED>" +
                  "<LOCPORT>8888</LOCPORT>" +
                  "<COMPORT>4</COMPORT>" +
                  "<LLSCREENTYPE>SCREEN_COLOR</LLSCREENTYPE>" +
                  "<REMOTPORT>6666</REMOTPORT>" +
                  "<NEWDATE>20130527</NEWDATE>" +
                  "<NEWUSER>SUN</NEWUSER>" +
                   "<LASTDATE>20130527</LASTDATE>" +
                  "<LASTUSER>SUN</LASTUSER>" +
                  "</SXDData>";
            result = proxy.GetInfo(rawMessage);
            #endregion

            #region=======3.7 LED_RegLED LED04================
            // 3.6. ½ØÍ¼
            //¿ÉÒÔÍ¨¹ýÖÐÐÄ¹ÜÀíÆ½Ì¨£¬·¢ËÍ½ØÍ¼Ö¸Áî£¬½«µ±Ç°LEDµÄÏÔÊ¾ÄÚÈÝÒÔÍ¼Æ¬µÄ·½Ê½·µ»Ø¡£
            command = "LED_RegLED";
            rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                  "<SXDData>" +
                  "<COMMAND>" + command + "</COMMAND>" +
                  "<LEDID>4</LEDID>" +
                  "<LLLEDPRE>  </LLLEDPRE>" +
                  "<LLLEDNUMBER>LED02</LLLEDNUMBER>" +
                  "<IPADDRESS>192.168.0.101</IPADDRESS>" +
                  "<DEVTYPE>DEVICE_TYPE_UDP</DEVTYPE>" +
                  "<DSPEED>SBR_57600</DSPEED>" +
                  "<LOCPORT>8888</LOCPORT>" +
                  "<COMPORT>4</COMPORT>" +
                  "<LLSCREENTYPE>SCREEN_COLOR</LLSCREENTYPE>" +
                  "<REMOTPORT>6666</REMOTPORT>" +
                  "<NEWDATE>20130527</NEWDATE>" +
                  "<NEWUSER>SUN</NEWUSER>" +
                   "<LASTDATE>20130527</LASTDATE>" +
                  "<LASTUSER>SUN</LASTUSER>" +
                  "</SXDData>";
            result = proxy.GetInfo(rawMessage);
            #endregion

        }
        private string GetLEDList()
        {
            #region=======4.9 LED_GetLEDList================
            command = "LED_GetLEDList";
            rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                  "<SXDData>" +
                  "<COMMAND>" + command + "</COMMAND>" +
                  "</SXDData>";
            result = proxy.GetInfo(rawMessage);
            #endregion
            return result;
        }
        private string FastenProgram()
        {
            #region=======4.9 LED_GetLEDList================
            command = "LED_FastenProgram";
            rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                  "<SXDData>" +
                  "<COMMAND>" + command + "</COMMAND>" +
                  "</SXDData>";
            result = proxy.GetInfo(rawMessage);
            #endregion
            return result;
        }        
        private string SwithPower(int nTurnOn, int nShowIP)
        { 
            command = "LED_SwitchPower";
            rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                  "<SXDData>" +
                      "<COMMAND>" + command + "</COMMAND>" +
                  "<LEDID>" + nLEDID + "</LEDID>" +
                  "<POWER>" + nTurnOn + "</POWER>" +
                  "</SXDData>";
            if (nShowIP == 1)
            {
                rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                    "<SXDData>" +
                    "<COMMAND>" + command + "</COMMAND>" +
                    "<LEDID>" + nLEDID + "</LEDID>" +
                    "<POWER>" + nTurnOn + "</POWER>" +
                    "<OUTPUTIP>" + nShowIP + "</OUTPUTIP>" +
                    "</SXDData>";
            }
            result = proxy.GetInfo(rawMessage);

            return result;
        }
        public void Start()
        {
            Logger.Debug("Start listener thread");
            if (proxy == null)
            {
                proxy = new SXDBLClient();
            }
            for (; ; )
            {
                Logger.Debug("Call service..");
                try
                {

                    RegPicture("A1.jpg");
                    RegPicture("A2.jpg");
                    RegPicture("A3.jpg");

                    #region============InsigmaLEDDriver_Init================
                    command = "InsigmaLEDDriver_Init";
                    rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                          "<SXDData>" +
                              "<COMMAND>" + command + "</COMMAND>" +
                          "</SXDData>";
                    result = proxy.GetInfo(rawMessage);
                    #endregion

                    SwithPower(1, 0);
                    SwithPower(0, 0);
                    StartUpAndShowIP();
                    SetBright(2);
                    result = GetBright();

                    Console.WriteLine("Bright" + result);
                    /*
                    #region=======3.6LED_CopyScreen================
                    // 3.6. ½ØÍ¼
                    //¿ÉÒÔÍ¨¹ýÖÐÐÄ¹ÜÀíÆ½Ì¨£¬·¢ËÍ½ØÍ¼Ö¸Áî£¬½«µ±Ç°LEDµÄÏÔÊ¾ÄÚÈÝÒÔÍ¼Æ¬µÄ·½Ê½·µ»Ø¡£
                    command = "LED_SwitchPower";
                    nTurnOn = 0;
                    rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                          "<SXDData>" +
                              "<COMMAND>" + command + "</COMMAND>" +
                          "<LEDID>" + nLEDID + "</LEDID>" +
                          "<POWER>" + nTurnOn + "</POWER>" +
                          "</SXDData>";
                    result = proxy.GetInfo(rawMessage);
                    #endregion
                    */
                    RegLED();
                    result=GetLEDList();
                    Console.Write(result); 
                    ScreenInit(128, 32);
                    #region============ LED_AddTextBlock直接显示宋体================
                    string szText = "达到本源西方金,x=10,y=2,宽=128,高=32,速度=1";
                    string szFontName = "宋体";
                    int lFontSize = 12;
                    int lFontColor = 234;
                    int nBold = 1;
                    int nUnderline = 1;
                    nWidth = 128;
                    nHeight = 32;
                    int nStrick = 1;
                    int nEffectType = 0;
                    int nSpeed = 1;
                    Int32 lTrasnparent = 1;
                    int startx = 10;
                    int starty = 2;
                    AddText(szText, szFontName, lFontSize, nEffectType, nSpeed);
                    #endregion

                    #region============ LED_AddBmpBlock直接显示图片================
                    string szBmp = "A1.jpg";
                    AddPicture(szBmp,10,2,128,32,0,1);        
                    #endregion

                    #region============ LED_AddTextBlock左滚文字================
                    szText = "左滚文字楷体,x=10,y=2,宽=128,高=32,速度=2";
                    nEffectType = 1;
					szFontName="楷体";
					lFontSize=14;
                    AddText(szText, szFontName, lFontSize, nEffectType, nSpeed);
                    #endregion

                    #region============ LED_AddBmpBlock左滚图片¬================
                    nEffectType = 1;
                    szBmp = "A2.jpg";
                    AddPicture(szBmp, 10, 2, 128, 32, 0, 1);
                    #endregion

                    #region============ LED_AddTextBlock右滚文字楷体================
                     szText = "右滚文字楷体,x=10,y=2,宽=128,高=32,速度=3";
                    nEffectType = 1;
					szFontName="楷体";
					lFontSize=14;
                    nEffectType = 2;
                    AddText(szText, szFontName, lFontSize, nEffectType, nSpeed);
                    #endregion

                    #region============ LED_AddBmpBlock右滚图片A3¬================
                    nEffectType = 2;
                    szBmp = "A3.jpg";
                    AddPicture(szBmp, 10, 2, 128, 32, 0, 1);
                    #endregion

                    #region============ LED_AddTextBlock上滚文字================
                    szText = "上滚文字楷体,x=10,y=2,宽=128,高=32,速度=3";                    
					szFontName="楷体";
					lFontSize=14;                
                    nEffectType = 3;
                    AddText(szText, szFontName, lFontSize, nEffectType, nSpeed);
                    #endregion

                    #region============ LED_AddBmpBlock上滚图片================
                    nEffectType = 3;
                    szBmp = "A1.jpg";
                    AddPicture(szBmp, 10, 2, 128, 32, 0, 1);
                    #endregion

                    #region============ LED_AddTextBlock下滚文字楷体================
                    szText = "下滚文字楷体,x=10,y=2,宽=128,高=32,速度=3";
					szFontName="楷体";
					lFontSize=14;                
                    nEffectType = 4;
                    AddText(szText, szFontName, lFontSize, nEffectType, nSpeed);
                    #endregion

                    #region============ LED_AddBmpBlock下滚图片================
                    nEffectType = 4;
                    szBmp = "A1.jpg";
                    AddPicture(szBmp, 10, 2, 128, 32, 0, 1);
                    #endregion               

                    AddClock();

                    EndProg();

                    Send2LED();
                    FastenProgram(); 
                }
                catch (Exception ex)
                {
                    Logger.Fatal(ex.ToString());
                }
                System.Threading.Thread.Sleep(Timeout);
            }

        }

    }
}

